class RoutesController < ApplicationController
  def index
    @routes = Route.order("nombre").all

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @routes }
    end
  end

  # GET /trips/1
  # GET /trips/1.xml
  def show
    @route = Route.find(params[:id])
		@stations = Station.find_by_sql(["SELECT A.* FROM stations A JOIN route_x_stations B ON (A.ID = B.STATION_ID) WHERE B.ROUTE_ID = ? ORDER BY B.posicionRuta",params[:id]])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @route }
    end
  end

  def new
    @route = Route.new
		@stations = Station.order("ciudad").all

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @routes }
    end
  end

  def create
    @route = Route.new(params[:route])
		@route.numAccidentes = 0

    if @route.save
			terminales = params[:terms]
			for i in 1..terminales.size
				if terminales["t#{i}"].size > 0 then
					rxs = RouteXStation.new
					rxs.route_id = @route.id
					rxs.station_id = terminales["t#{i}"].to_i
					rxs.posicionRuta = i
					
					if !rxs.save then
						error = true
					end
				end
			end
			
			respond_to do |format|
		    format.html { redirect_to(stations_path, :notice => "La ruta #{@route.nombre} se creo correctamente.") }
		    format.xml  { render :xml => @route, :status => :created, :location => @route }
			end
    else
			respond_to do |format|
		    format.html { render :action => "new" }
		    format.xml  { render :xml => @route.errors, :status => :unprocessable_entity }
		  end
    end
  end

  def edit
    @route = Route.find(params[:id])
  end

	def update
    @route = Route.find(params[:id])

    if @route.update_attributes(params[:station])
	    respond_to do |format|
	      format.html { redirect_to(stations_path, :notice => 'Station was successfully updated.') }
	      format.xml  { head :ok }
			end
    else
	    respond_to do |format|
		    format.html { render :action => "edit" }
		    format.xml  { render :xml => @route.errors, :status => :unprocessable_entity }
	    end
    end
  end

  def destroy
    @route = Route.find(params[:id])
    @route.destroy

    respond_to do |format|
      format.html { redirect_to(stations_url) }
      format.xml  { head :ok }
    end
  end
end
